package org.goodsmanager.controller;

import org.goodsmanager.entity.Order;
import org.goodsmanager.entity.User;
import org.goodsmanager.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpSession;
import java.util.List;

/**
 * 订单列表控制器
 */
@Controller
@RequestMapping("/orders")
public class OrderListController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 订单列表页面
     */
    @GetMapping("")
    public String orderList(
            @RequestParam(defaultValue = "all") String status,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model,
            HttpSession session) {
        
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 计算偏移量
        int offset = (page - 1) * size;
        
        // 获取订单列表
        List<Order> orders;
        if ("all".equals(status)) {
            orders = orderService.getOrdersByUserId(Long.valueOf(user.getId()));
        } else {
            orders = orderService.getOrdersByUserIdAndStatus(Long.valueOf(user.getId()), status);
        }
        
        // 获取订单总数
        int totalOrders = orderService.countOrdersByUserId(Long.valueOf(user.getId()));
        
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalOrders / size);
        
        model.addAttribute("orders", orders);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("totalOrders", totalOrders);
        model.addAttribute("status", status);
        model.addAttribute("size", size);
        
        return "shop/order-list";
    }
    
    /**
     * 订单详情页面
     */
    @GetMapping("/{id}")
    public String orderDetail(@PathVariable Long id, Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        Order order = orderService.getOrderById(id);
        
        // 检查订单是否存在且属于当前用户
        if (order == null || !order.getUserId().equals(user.getId())) {
            return "redirect:/orders";
        }
        
        model.addAttribute("order", order);
        
        return "shop/order-detail";
    }
}